package com.lut.edu.apm.commodityCenter.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lut.edu.apm.commodityCenter.pojo.CommodityLibrary;
import com.lut.edu.apm.commodityCenter.pojo.CommodityOrder;
import com.lut.edu.apm.commodityCenter.service.CommodityLibraryService;
import com.lut.edu.apm.commodityCenter.service.CommodityOrderService;
import com.lut.edu.apm.commodityCenter.service.ProductInquiry;
import com.lut.edu.apm.commodityCenter.unit.RequestHTTPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Zhao Suzhen
 * @date `2024/4/13`
 */
@Service
public class ProductInquiryImpl implements ProductInquiry {

    private Logger logger = LoggerFactory.getLogger(ProductInquiry.class);

    @Autowired
    CommodityLibraryService commodityLibraryService;

    @Autowired
    CommodityOrderService commodityOrderService;

    @Override
    public CommodityLibrary queryProductIn(String productId) {
        CommodityLibrary commodityLibrary;
        commodityLibrary = commodityLibraryService.queryById(productId);
        if (null == commodityLibrary) {
            commodityLibrary = queryApi(productId);
        }
        return commodityLibrary;
    }

    @Override
    public CommodityOrder queryProduct(String productId) {
        return commodityOrderService.queryById(productId);
    }

    private CommodityLibrary queryApi(String productId) {
        String url = "http://api.tanshuapi.com/api/barcode/v1/index";
        Map<String, String> param = new HashMap<>();
        param.put("key", "38fa2ffdce1a7719e9ca3b614432b185");
        param.put("barcode", productId);
        String response = new RequestHTTPUtil().get(url, param);
        JSONObject resp = JSONObject.parseObject(response);
        if (1 == (int) resp.get("code")) {
            CommodityLibrary commodityLibrary = new CommodityLibrary();
            JSONObject data = (JSONObject) resp.get("data");
            commodityLibrary.setItemNo(productId);
            commodityLibrary.setItemName(String.valueOf(data.get("goods_name")));
            commodityLibrary.setPym(String.valueOf(data.get("price")));
            commodityLibrary.setItemSize(String.valueOf(data.get("net_weight")));
            commodityLibrary.setUnitNo(String.valueOf(data.get("keyword")));
            commodityLibrary.setProductArea(String.valueOf(data.get("origin_country")));
            logger.info("自API获取商品：" + response);
            commodityLibraryService.save(commodityLibrary);
            return commodityLibrary;
        }
        // TODO 查询到的信息入库
        return null;
    }
}
